package com.x.redis;

import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.SentinelServersConfig;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.List;
import java.util.Objects;

/**
 * the class of advance
 *
 * <p>
 * .
 *
 * @author little_lunatic
 * @date 2024-07-25
 */
@Slf4j
//@Configuration
public class RedisConfig {

    // 直接使用starter注入的redis配置信息
    @Autowired
    private RedisProperties redisProperties;

    /**
     * 1.使用redisTemplate需要的配置类
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        // 使用StringRedisSerializer来序列化和反序列化键值
        template.setKeySerializer(RedisSerializer.string());
        template.setValueSerializer(RedisSerializer.string());
        return template;
    }

    /**
     * 2.jedis. 非线程安全
     *
     * @return
     */
    @Bean
    public Jedis jedis() {
        return new Jedis("127.0.0.1", 6379);
    }

    /**
     * 3.jedis pool. 线程安全
     *
     * @return
     */
    @Bean("jpool")
    public JedisPool jedisPool() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(10);
        poolConfig.setMaxIdle(10);
        poolConfig.setMinIdle(0);
        poolConfig.setMaxWaitMillis(500);
        return new JedisPool(poolConfig,"127.0.0.1",6379,1000,"qaq123..");
    }


    /**
     * 4.redisson
     *
     * @return
     */
    @Bean
    public RedissonClient redissonClient() {

        // 哨兵
        RedisProperties.Sentinel sentinel = redisProperties.getSentinel();
        if (Objects.nonNull(sentinel)) {
            log.info("redis is sentinel mode");
            return redissonSentinel();
        }
        // 集群
        RedisProperties.Cluster cluster = redisProperties.getCluster();
        if (Objects.nonNull(cluster)) {
            log.info("redis is cluster mode");
            return redissonCluster();
        }
        // 单机
        String host = redisProperties.getHost();
        if (StringUtils.isNotBlank(host)) {
            log.info("redis is single mode");
            return redissonSingle();
        }

        return null;
    }

    /**
     * 单机模式
     *
     * @return
     */
    private RedissonClient redissonSingle() {
        String host = redisProperties.getHost();
        String password = redisProperties.getPassword();
        int port = redisProperties.getPort();
        // 设置超时时间
        long timeout = 0;
        if (!redisProperties.getTimeout().isZero()) {
            timeout = redisProperties.getTimeout().toMillis();
        }
        // 声明一个配置类
        Config config = new Config();
        SingleServerConfig serverConfig = config.useSingleServer()
                .setAddress("redis://" + host + ":" + port)
                .setTimeout((int) timeout)
                .setPingConnectionInterval(60000)
                .setConnectionPoolSize(100)
                .setConnectionMinimumIdleSize(10);
        // 判断密码
        if (!StringUtils.isEmpty(password)) {
            serverConfig.setPassword(password);
        }
        return Redisson.create(config);
    }


    /**
     * 集群模式
     *
     * @return
     */
    private RedissonClient redissonCluster() {
        // 192.168.116.156:1901,192.168.116.156:1902
        List<String> nodes = redisProperties.getCluster().getNodes();
        String password = redisProperties.getPassword();
        // 声明一个配置类
        Config config = new Config();
        ClusterServersConfig clusterServersConfig = config.useClusterServers();
        // 扫描间隔
        clusterServersConfig.setScanInterval(2000);
        // 判断密码
        if (!StringUtils.isEmpty(password)) {
            clusterServersConfig.setPassword(password);
        }
        // 添加redis节点
        for (String node : nodes) {
            clusterServersConfig.addNodeAddress("redis://" + node);
        }
        return Redisson.create(config);
    }

    /**
     * 哨兵模式
     * 
     * @return
     */
    private RedissonClient redissonSentinel() {
        String masterName = redisProperties.getSentinel().getMaster();
        // 127.0.0.1:26389,127.0.0.1:26379
        List<String> nodes = redisProperties.getSentinel().getNodes();
        String password = redisProperties.getPassword();
        // 声明一个配置类
        Config config = new Config();
        SentinelServersConfig sentinelServersConfig = config.useSentinelServers();
        // 扫描间隔
        sentinelServersConfig.setScanInterval(2000);
        // 判断密码
        if (!StringUtils.isEmpty(password)) {
            sentinelServersConfig.setPassword(password);
        }
        sentinelServersConfig.setMasterName(masterName);

        nodes.forEach(s->{
            s = "redis://" + s;
        });
        // 添加redis节点
        sentinelServersConfig.addSentinelAddress(nodes.toArray(new String[0]));
        return Redisson.create(config);
    }
    
    
}
